package world.criver.mm_vworld_server.function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import world.criver.crc.CRC;
import world.criver.mm_vworld_server.config.conConfig;
import world.criver.mm_vworld_server.data.daSave;
import world.criver.mm_vworld_server.data.daServer;
import world.criver.mm_vworld_server.modular.moClient;
import world.criver.mm_vworld_server.modular.moPlayer;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

@Component
public class funClient {
    @Autowired
    private conConfig conConfig;

    private CRC crc=new CRC();
    /**
     * 指定客户端发送消息
     * @param id
     * @param message
     */
    public boolean send(String id,String message){
        try {
            System.out.println("发送："+id+"\t"+message);
            moClient client = daServer.clients.get(id);
            if(client.getWriter()==null)client.setWriter(new BufferedWriter(new OutputStreamWriter(client.getClient().getOutputStream())));
            message=crc.encrypt(conConfig.getEncryptKey(), message);
            client.getWriter().write(message+"\n");
            client.getWriter().flush();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据client id获取玩家信息
     * @param id
     * @return
     */
    public moPlayer getPlayer(String id){
        for(String key:daServer.clients.keySet())if(key.equals(id)){
            if(daSave.players.containsKey(daServer.clients.get(id).getNickname()))return daSave.players.get(daServer.clients.get(id).getNickname());
        }
        return null;
    }
}
